<?php
/*
 * @Author: CHINAKAIYUAN<sunkaiyuan@namenode.cn>
 * @Date: 2022-02-04 16:53:56
 * @LastEditTime: 2023-10-03 13:52:21
 * @LastEditors: 孙开源 && sunkaiyuan@namenode.cn
 * @Description: 
 */

namespace App\Http\Services\Market;

use App\Http\Services\Service;
use App\Repositories\MarketComplaintRepository;
use App\Repositories\MarketComplaintDetailsRepository;
use App\Repositories\MarketDeliveryDetailsRepository;
use App\Repositories\MarketOrderRepository;
use Illuminate\Support\Facades\DB;

/**
 * @property MarketComplaintRepository $repository
 * @property MarketComplaintDetailsRepository $details 
 * @property MarketDeliveryDetailsRepository $market
 * @property MarketOrderRepository $order
 */
class ComplaintService extends Service
    {
    public $details;

    public function boot(
        MarketComplaintRepository $repository,
        MarketComplaintDetailsRepository $details,
        MarketDeliveryDetailsRepository $market,
        MarketOrderRepository $order
    ) {
        $this->repository = $repository;
        $this->details    = $details;
        $this->market     = $market;
        $this->order      = $order;
        }

    public function list()
        {
        $data = $this->repository->condition(request())->getGrid();
        return $data;
        }
    public function details()
        {
        $data = $this->details->condition(request())->getList();

        return $data;
        }
    protected function save()
        {
        $data = request()->toArray();
        $id   = is_numeric($data['id'] ?? "") ? $data['id'] : 0;

        if ($id !== 0) {
            $gdata = $this->repository->whereId($id)->getOne();

            if ($gdata->status_id != '0') {
                fail("订单状态[{$gdata->status->name}],禁止编辑");
                }
            //反审核未刷新情况下，status_id=1，导致编辑后有问题！
            $data['status_id'] = 0;
            }
        // 折价
        if ($data['complaint_id'] == 4 && (!is_numeric($data['discount'] ?? 'error') || $data['discount'] == 0)) {
            fail("折价必须填单价");
            }
        //补发 换货
        if ($data['complaint_id'] == 5 || $data['complaint_id'] == 3) {
            if (!is_array($data['details']) || count($data['details']) == 0)
                fail("必须选择库存！");
            }
        else {
            if (is_array($data['details']) && count($data['details']) > 0)
                fail("不应选择库存！");
            }

        $gdata['department_id'] = auth()->user()->department_id;
        $gdata                  = $this->repository->autosave($data);
        $gdata->details->filter(function ($v) use ($gdata)
            {
            $v->code     = $gdata->code;
            $v->is_draft = 0;
            $v->save();
            });
        if ($gdata->complaint_id == 2) {
            if ($gdata->red_retial->quantity < $gdata->quantity) {
                fail("退货数量不应大于发货数量！！");
                }
            }
        }

    private function saveDetails($data)
        {
        $adata = $data->toArray();
        // $data     = $data->toArray(); 

        $details = $data->details->map(function ($v) use ($data)
            {
            $res = $v->toArray();
            unset($res['id']);
            $res['code']                  = $data['code'];
            $res['red_id']                = $data['red_id'];
            $res['billdate']              = date("Y-m-d");
            $res['status_id']             = $data['status_id'];
            $res['singler_id']            = $data['singler_id'];
            $res['customer_id']           = $data['customer_id'];
            $res['complaint_id']          = $data['complaint_id'];
            $res['department_id']         = $data['department_id'];
            $res['se_amount']             = $res['amount'] = $v['amount'];
            $res['se_quantity']           = $res['md_quantity'] = $res['quantity'] = $v['quantity'];
            $res['se_auxiliary_quantity'] = $res['auxiliary_quantity'] = $v['auxiliary_quantity'];
            $res['is_draft'] = 0;
            return $res;
            })->toArray();

        unset($adata['apply_grade'], $adata['relation_code']);
        if (in_array($data->complaint_id, [2, 3])) {
            $adata['main_id']               = $adata['id'];
            $adata['id']                    = 0;
            $adata['billdate']              = date("Y-m-d");
            $adata['se_amount']             = $adata['amount'] = ($data['amount'] ?? 0) * -1;
            $adata['se_quantity']           = $adata['md_quantity'] = $adata['quantity'] = $data['quantity'] * -1;
            $adata['red_quantity']          = 0;
            $adata['se_auxiliary_quantity'] = $adata['auxiliary_quantity'] = $data['auxiliary_quantity'] * -1;
            $details[] = $adata;
            }
        else if ($data->complaint_id == 4) {
            $adata['main_id']     = $adata['id'];
            $adata['id']          = 0;
            $adata['amount']      = 0 - $adata['discount'];
            $adata['material_id'] =
                $adata['type_id'] =
                $adata['lot_id'] =
                $adata['se_quantity'] =
                $adata['quantity'] =
                $adata['red_quantity'] =
                $adata['se_auxiliary_quantity'] =
                $adata['price'] =
                $adata['auxiliary_quantity'] = 0;
            $adata['dyelot'] = "";
            unset($adata['discount']);
            $adata['billdate'] = date("Y-m-d");
            $details[]         = $adata;
            }

        return array_map(function ($v)
            {
            return $this->market->autosave($v);
            }, $details);
        }
    private function inStorage($gdata, $flag = true)
        {
        $red = $gdata->red;

        if ($flag) {
            $gdata->addStorage('销售客诉', $gdata->code, $gdata->quantity, $gdata->auxiliary_quantity);
            $red->red_quantity -= $gdata->quantity;
            if ($red->red_quantity + $red->quantity < 0) {
                fail("退货数量比发货数量多！创建售后单失败！");
                }
            }
        else {
            $gdata->noaddStorage();
            $red->red_quantity += $gdata->quantity;
            }
        $red->save();
        }
    private function outStorage($detail, $flag = true)
        {
        return $flag ? $detail->useStorage('销售客诉', $detail->code)->subStorage() : $detail->nosubStorage()->nouseStorage();
        }

    protected function audit()
        {
        return $this->getOrder()->filter(function ($Order)
            {
            if ($Order->status_id != 0) {
                fail("订单状态[{$Order->status->name}],审核失败");
                }
            auditSave($Order);
            $this->saveDetails($Order);
            //退货
            if (in_array($Order->complaint_id, [2, 3])) {
                //退货情况下，订单发货，要恢复已发货库存！
                if ($Order->complaint_id == 2 && $Order->order_detail_id > 0) {
                    $this->order->delivery($Order->order_detail_id, 0 - $Order->quantity);
                    }
                $this->inStorage($Order);
                }
            //出货
            $Order->details->filter(function ($v)
                {
                $this->outStorage($v);
                });
            });
        }
    /**
     * Summary of noaudit
     * @return mixed
     */
    protected function noaudit()
        {
        return $this->getOrder()->filter(function ($Order)
            {
            if ($Order->status_id != 1) {
                fail("订单状态[{$Order->status->name}],反审失败");
                }
            $Order->retails->filter(function ($v)
                {
                $v->forceDelete();
                });
            if (in_array($Order->complaint_id, [2, 3])) {
                //退货情况下，订单发货，要减去已发货库存！
                if ($Order->complaint_id == 2 && $Order->order_detail_id > 0) {
                    $this->order->delivery($Order->order_detail_id, $Order->quantity);
                    }
                $this->inStorage($Order, false);
                }
            $Order->details->filter(function ($v)
                {
                $this->outStorage($v, false);
                });
            auditSave($Order, false);
            });
        }


    private function getOrder()
        {
        return $this->repository->whereIn("id", $this->getRequestIds())->get();
        }
    protected function delete()
        {

        return $this->repository->whereIn("id", $this->getRequestIds())->get()->filter(function ($v)
            {
            if ($v->status_id != '0') {
                fail("订单状态[{$v->status->name}],禁止编辑");
                }
            //删除明细
            $v->details->filter(function ($detail)
                {
                $detail->delete();
                });
            $v->delete();
            });
        }

    public function printReport()
        {
        $data               = $this->repository->relation()->whereIn("id", $this->getRequestIds())->get();
        $aftersalekind_name = $customer_name = null;
        $data = $data->map(function ($v) use (&$aftersalekind_name, &$customer_name)
            {
            if ($aftersalekind_name == null) {
                $aftersalekind_name = $v->complaint->name;
                }
            else {
                if ($aftersalekind_name != $v->complaint->name) {
                    fail("必须选择同一类别单据！");
                    }
                }
            if ($customer_name == null) {
                $customer_name = $v->customer->name;
                }
            else {
                if ($customer_name != $v->customer->name) {
                    fail("必须选择同一客户单据！");
                    }
                }
            $v['aftersalekind_name'] = '售后' . $aftersalekind_name;
            return $v;
            // aftersalekind_name
            });
        return createReport($data->toArray());
        }
    protected function faudit()
        {
        $financeremark = request("financeremark") ?? "";
        $query         = $this->repository->whereIn("id", $this->getRequestIds());
        if (isEmpty($financeremark)) {
            return $query->finance();
            }
        else
            return $query->get()->filter(function ($order) use ($financeremark)
                {
                if ($order->status_id != 1) {
                    fail("订单状态【{$order->status->name}】,无法财审！");
                    }
                $order->financeremark = $financeremark;
                $order->finance();
                });
        }
    }